'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Chaincode query
 */

let Fabric_Client = require('fabric-client');
let path = require('path');
let fs = require('fs');
//
let fabric_client = new Fabric_Client();
let s_path = path.resolve(__dirname, `../hfc-key-store-org1/ca.crt`);
let obj = {
    channel: "mychannel1",
    peer: "grpcs://192.168.0.138:7051",
    username: "peer0.org1.example.com",
    chaincodeId: 'demo',
    fcn: 'query',
    args: ['a'],
    crt: fs.readFileSync(s_path)
};

let channel = fabric_client.newChannel(obj.channel);
let peer = fabric_client.newPeer(obj.peer, {
    "pem": Buffer.from(obj.crt).toString(),
    'ssl-target-name-override': obj.username
});
channel.addPeer(peer);

//
let member_user = null;
let store_path = path.resolve(__dirname, '../hfc-key-store-org1');

console.log('Store path:' + store_path);

Fabric_Client.newDefaultKeyValueStore({
    path: store_path
}).then((state_store) => {
    fabric_client.setStateStore(state_store);
    let crypto_suite = Fabric_Client.newCryptoSuite();

    let crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
    crypto_suite.setCryptoKeyStore(crypto_store);
    fabric_client.setCryptoSuite(crypto_suite);

    return fabric_client.getUserContext(obj.username, true);
}).then((user_from_store) => {
    if (user_from_store && user_from_store.isEnrolled()) {
        console.log('Successfully loaded user1 from persistence');
        member_user = user_from_store;
    } else {
        throw new Error('Failed to get user1.... run registerUser.js');
    }

    const request = {
        chaincodeId: obj.chaincodeId,
        fcn: obj.fcn,
        args: obj.args
    };

    return channel.queryByChaincode(request);
}).then((query_responses) => {
    console.log("Query has completed, checking results");
    if (query_responses && query_responses.length === 1) {
        if (query_responses[0] instanceof Error) {
            console.error("error from query = ", query_responses[0]);
        } else {
            console.log("Response is ", query_responses[0].toString());
        }
    } else {
        console.log("No payloads were returned from query");
    }
}).catch((err) => {
    console.error('Failed to query successfully :: ' + err);
});
